package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    @Override
    public String saveVideo(Video video) {

        try {
            //校验必须字段
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getVideoUrl(), video.getPicUrl())) {
                return null;
            }

            //设置id 发布时间
            video.setId(ObjectId.get());
            video.setVid(idService.createId(IdType.VIDEO));
            video.setCreated(System.currentTimeMillis());

            //保存到mongodb中
            mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("发布视频失败  video = " + video, e);
        }

        return null;
    }

    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从redis中获取推荐的视频数据
        String redisData = redisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_" + userId);
        List<Long> vids = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');

            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束

            //将推荐的视频的id获取到
            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vidList.size();
        }

        //推荐视频共二十条，如果推荐视频显示完就该查询系统的视频数据
        if (CollUtil.isEmpty(vids)) {
            //计算视频所到页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);
            PageRequest pageRequest = PageRequest.of(page - 1 - totalPage, pageSize, Sort.by(Sort.Order.desc("created")));

            //根据条件从MongoDB中查询到视频数据
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);


            pageInfo.setRecords(videoList);
            return pageInfo;
        }

        //根据vid查询视频数据
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {

        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {

        //校验userId 和 followUserId
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        try {
            //判断是否关注了
            if (isFollowUser(userId, followUserId)) {
                return false;
            }

            FollowUser followUser = new FollowUser();

            followUser.setCreated(System.currentTimeMillis());
            followUser.setFollowUserId(followUserId);
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);

            //写入mongodb
            mongoTemplate.save(followUser);

            //写入redis
            redisTemplate.opsForHash().put(VIDEO_FOLLOW_USER_KEY_PREFIX + userId, followUserId + "", "1");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        //校验userId 和 followUserId
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        //判断是否关注了
        if (!isFollowUser(userId, followUserId)) {
            return false;
        }

        //删除mongodb和redis中存储的数据
        Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
        DeleteResult result = mongoTemplate.remove(query, FollowUser.class);
        if(result.getDeletedCount()>0){
            redisTemplate.opsForHash().delete(VIDEO_FOLLOW_USER_KEY_PREFIX+userId,followUserId+"");

            return true;
        }

        return false;

    }

    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        return redisTemplate.opsForHash().hasKey(
                VIDEO_FOLLOW_USER_KEY_PREFIX + userId,String.valueOf(followUserId));
    }

//    @Override
//    public Boolean followUser(Long userId, Long followUserId) {
//        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
//            return false;
//        }
//
//        try {
//            //需要将用户的关注列表，保存到redis中，方便后续的查询
//            //使用redis的hash结构
//            if (this.isFollowUser(userId, followUserId)) {
//                return false;
//            }
//
//            FollowUser followUser = new FollowUser();
//            followUser.setId(ObjectId.get());
//            followUser.setUserId(userId);
//            followUser.setFollowUserId(followUserId);
//            followUser.setCreated(System.currentTimeMillis());
//
//            this.mongoTemplate.save(followUser);
//
//            //保存数据到redis
////            String redisKey = this.getVideoFollowUserKey(userId);
////            String hashKey = String.valueOf(followUserId);
//            this.redisTemplate.opsForHash().put(VIDEO_FOLLOW_USER_KEY_PREFIX + userId, followUserId, "1");
//
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return false;
//    }
//
//    @Override
//    public Boolean disFollowUser(Long userId, Long followUserId) {
//        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
//            return false;
//        }
//
//        if (!this.isFollowUser(userId, followUserId)) {
//            return false;
//        }
//
//        //取消关注，删除关注数据即可
//        Query query = Query.query(Criteria.where("userId").is(userId)
//                .and("followUserId").is(followUserId)
//        );
//        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
//        if (result.getDeletedCount() > 0) {
//            //同时删除redis中的数据
//            String redisKey = this.getVideoFollowUserKey(userId);
//            String hashKey = String.valueOf(followUserId);
//            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
//
//            return true;
//        }
//
//        return false;
//    }
//
//    @Override
//    public Boolean isFollowUser(Long userId, Long followUserId) {
//        String redisKey = this.getVideoFollowUserKey(userId);
//        String hashKey = String.valueOf(followUserId);
//        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
//    }
//
//    private String getVideoFollowUserKey(Long userId) {
//        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
//    }

}
